<template>
  <el-dialog :title="title" :visible.sync="dialogShow" @close="closeDialog">
    <!-- ! 表单 -->
    <el-form :model="formData" ref="form" :rules="formRules" label-width="140px">
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="formData.name"></el-input>
      </el-form-item>
      <!-- 如果表单里面存在下拉、单选、多选、树、复杂的空间，那么表单绘制将是一个复杂的过程。 -->
      <el-form-item label="角色描述" prop="description">
        <el-input v-model="formData.description" type="textarea" rows="2"></el-input>
      </el-form-item>
      <el-row type="flex" justify="center">
        <el-button size="small" type="primary" @click="btnOk">确定</el-button>
        <el-button size="small" @click="dialogShow = false">取消</el-button>
      </el-row>
    </el-form>
  </el-dialog>
</template>
<script>
import { addRoleApi, editRoleApi, getRoleInfoApi } from '@/api/setting'
export default {
  name: "addRole",
  data() {
    return {
      dialogShow: false,
      formData: {
        name: '',
        description: ''
      },
      formRules: {
        name: [{ required: true, message: '请输入', trigger: 'blur' }],
        description: [{ required: true, message: '请输入', trigger: 'blur' }],
      }
    };
  },
  computed: {
    title() {
      return this.formData.id ? '修改' : '新增'
    }
  },
  methods: {
    // 表单提交事件
    async btnOk() {
      // 1.表单校验
      try {
        await this.$refs.form.validate()
      } catch (error) {
        return console.log(error)
      }
      // 2.发生请求
      // 3.成功提示
      if (this.formData.id) {
        await editRoleApi(this.formData)
        this.$message.success('修改成功')
      } else {
        await addRoleApi(this.formData)
        this.$message.success('新增成功')
      }
      // 4.列表更新 
      this.$emit('updateList')
      // 5.关闭弹框
      this.dialogShow = false
    },
    // 弹框关闭事件
    closeDialog() {
      // 重置表单
      this.formData = {
        name: '',
        description: ''
      }
      // 移除校验  
      this.$refs.form.clearValidate()
    },
    // 获取回显数据
    async getRoleInfo(id) {
      // 获取修改行完整的数据
      let res = await getRoleInfoApi(id)
      // 回显表单
      this.formData = res
      // 弹框打开
      this.dialogShow = true
    }
  },
};
</script>
<style></style>
